package com.qf.commons.core.listener;

import org.slf4j.MDC;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.GenericApplicationListener;
import org.springframework.context.event.GenericApplicationListenerAdapter;
import org.springframework.core.Ordered;
import org.springframework.core.ResolvableType;
import org.springframework.core.env.ConfigurableEnvironment;

/**
 * @program: education-test
 * @author: tiger
 * @create: 2024-10-24 16:47
 * @Description : 监听Springboot环境准备事件，进行相对应处理 - 设置MDC
 */

public class LogMDCHandlerListener implements GenericApplicationListener {


    @Override
    public boolean supportsEventType(ResolvableType resolvableType) {
        return resolvableType.isAssignableFrom(ApplicationEnvironmentPreparedEvent.class);
    }

    @Override
    public boolean supportsSourceType(Class<?> sourceType) {
        return true;
    }

    @Override
    public void onApplicationEvent(ApplicationEvent applicationEvent) {
        ApplicationEnvironmentPreparedEvent event = (ApplicationEnvironmentPreparedEvent) applicationEvent;
        ConfigurableEnvironment environment = event.getEnvironment();
        String property = environment.getProperty("spring.application.name");
        MDC.put("filename", property);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 19;
    }
}
